package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.model.CommissionFreezeLevelSettings;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

@Component
public class OverdueOrdersImporter extends AbstractOrdersImporter{

  private Logger logger = LoggerFactory.getLogger(OverdueOrdersImporter.class);
  @Autowired
  DataSourceTransactionManager dataSourceTransactionManager;
  @Autowired
  TransactionDefinition transactionDefinition;
  @Override
  void doDealWithOrder(Orders orders, Orders previousOrder, Long parentUserId, Long parentPUserId,
      User user, User oneLevelUser) {
    logger.debug("deal with overdue orders");
    TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
    try {
      // 如果先前数据库没有订单，那么用户相应订单数加1
      if(previousOrder == null){
        countUserOrdersNum(orders);
      }
      // 如果数据库有记录，那么更新订单信息，没有则直接插入
      saveOrUpdateOrders(orders,previousOrder);
      // 删除收益记录
      deleteUserIncomeWhenOverDue(orders);
      dataSourceTransactionManager.commit(transactionStatus);
    }catch (Exception ex){
      logger.error("overdueOrder Exception is : {}",ex);
      dataSourceTransactionManager.rollback(transactionStatus);
    }

  }

  @Override
  protected void createIncomeRecord(Orders orders, Long userId, Long parentUserId,
      Long parentPuserId, Orders previousOrders,
      CommissionFreezeLevelSettings freezeCommissionSettings) {

  }

}
